const query = require('../db/mysql')
const { success, error } = require('../model/model')
class CarController {
    getCarList = async (ctx) => {
    
        const { user_id } = ctx.request.body
        const sql = `select * from carts where user_id="${user_id}"`
        const data = await query(sql)   

        const allP = data.map(item => {
            return query(`select * from shops where id="${item.shop_id}"`)
        })
        const shops = await Promise.all(allP)
        const newData = data.map((item, index) => {
            return { ...shops[index][0], ...item }
        })
        ctx.body = success(newData)
    }
    addToCar=async(ctx)=>{
        const {user_id,shop_id}=ctx.request.body
        const isHaveSql=`select * from cars where user_id="${user_id}" and shop_id="${shop_id}"`
        const isHave=await query(isHaveSql)
        let sql=''
        if(isHave.length){
            console.log(isHave);
            const nowData=isHave[0]
            sql=`update car set count="${nowData.count+=1}" where id="${nowData.id}"`
        }else{
            sql=`insert into car(user_id,shop_id,count) values("${user_id}","${shop_id}",1)`
        }
        const data=await query(sql)
        if(data.affectedRows===1){
            ctx.body=success('添加成功')
        }else{
            ctx.body=error('添加失败')
        }
    }

}
module.exports = new CarController()